package samples.java.jdbc;

import java.sql.*;
import java.time.LocalDate;

/**
 * Hello world!
 */
public class JdbcMysqlSamples {
    public static void main(String[] args) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {

        }

        final String url = "jdbc:mysql://localhost:3306/ops_iam?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false";
        final String user="root";
        final String password = "Bespin#123";

        try {
            Connection conn = DriverManager.getConnection(url, user, password);

            final String deleteSql = "delete from application";
            PreparedStatement deleteStatement = conn.prepareStatement(deleteSql);
            int deleteRowCount = deleteStatement.executeUpdate();
            System.out.println("delete application row count: " + deleteRowCount);

            final String insertSql = "insert into application (code, name, remark, created_by, updated_by, created_time, updated_time) " +
                    "values (?, ?, ?, ?, ?, ?, ?)";
            PreparedStatement insertStatement = conn.prepareStatement(insertSql);
            insertStatement.setString(1, "code001");
            insertStatement.setString(2, "iam");
            insertStatement.setString(3, "remark");
            insertStatement.setString(4, "system");
            insertStatement.setString(5, "system");
            insertStatement.setDate(6, java.sql.Date.valueOf(LocalDate.now()));
            insertStatement.setDate(7, java.sql.Date.valueOf(LocalDate.now()));
            int insertRows = insertStatement.executeUpdate();
            System.out.println("insert application rows count: " + insertRows);

            final String selectSql = "select * from application";

            Statement selectStatement = conn.createStatement();
            ResultSet domainRs = selectStatement.executeQuery(selectSql);
            while (domainRs.next()) {
                System.out.println("code: " + domainRs.getString("code") + " name: " + domainRs.getString("name")
                + " remark: " + domainRs.getString("remark")
                + " createBy: " + domainRs.getString("created_by")
                + " updateBy: " + domainRs.getString("updated_by"));
            }

            domainRs.close();
            deleteStatement.close();
            insertStatement.close();
            selectStatement.close();
            conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (Exception ex) {

        }
    }
}
